import React, { useEffect } from 'react';
import { Modal, Form, Input, Select, InputNumber, Switch } from 'antd';
import { Icon } from '@iconify/react';
import type { Menu } from '@/types';
import type { FormMode } from '@/types';
import { IconPicker, DictionarySelect } from '@/components';

const { Option } = Select;

interface MenuFormModalProps {
  visible: boolean;
  mode: FormMode;
  menus: Menu[];
  initialValues?: Menu;
  onSubmit: (values: any) => Promise<void>;
  onCancel: () => void;
}

const MenuFormModal: React.FC<MenuFormModalProps> = ({
  visible,
  mode,
  menus,
  initialValues,
  onSubmit,
  onCancel,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = React.useState(false);

  useEffect(() => {
    if (visible) {
      if (initialValues) {
        form.setFieldsValue(initialValues);
      } else {
        form.resetFields();
      }
    }
  }, [visible, initialValues, form]);

  // 将树形菜单转换为选项
  const convertMenusToOptions = (menuList: Menu[], level = 0): any[] => {
    const result: any[] = [];
    menuList.forEach(menu => {
      result.push({
        label: `${'  '.repeat(level)}${menu.title}`,
        value: menu.id,
      });
      if (menu.children && menu.children.length > 0) {
        result.push(...convertMenusToOptions(menu.children, level + 1));
      }
    });
    return result;
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      await onSubmit(values);
      form.resetFields();
    } catch (error) {
      console.error('Form validation failed:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  // 监听类型变化，显示相关提示
  const selectedIcon = Form.useWatch('icon', form);

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          {selectedIcon && <Icon icon={selectedIcon} style={{ fontSize: '20px', color: '#1890ff' }} />}
          <span>{mode === 'create' ? '新增菜单' : '编辑菜单'}</span>
        </div>
      }
      open={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      confirmLoading={loading}
      width={680}
      okText={mode === 'create' ? '创建' : '保存'}
      cancelText="取消"
      styles={{
        body: {
          maxHeight: '65vh',
          overflowY: 'auto',
          paddingRight: '8px',
        }
      }}
    >
      <Form form={form} layout="vertical">
        <Form.Item
          name="type"
          label="菜单类型"
          rules={[{ required: true, message: '请选择菜单类型' }]}
          initialValue="menu"
        >
          <DictionarySelect code="menu_type" placeholder="请选择菜单类型" />
        </Form.Item>

        <Form.Item name="parentId" label="父级菜单">
          <Select placeholder="请选择父级菜单（不选为顶级菜单）" allowClear>
            {convertMenusToOptions(menus).map(opt => (
              <Option key={opt.value} value={opt.value}>{opt.label}</Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="name"
          label="菜单名称"
          rules={[{ required: true, message: '请输入菜单名称' }]}
          tooltip="英文标识，用于代码中引用"
        >
          <Input placeholder="例如：SystemMenu" />
        </Form.Item>

        <Form.Item
          name="title"
          label="显示标题（中文）"
          rules={[{ required: true, message: '请输入显示标题' }]}
        >
          <Input placeholder="例如：系统管理" />
        </Form.Item>

        <Form.Item name="english" label="显示标题（英文）">
          <Input placeholder="例如：System Management" />
        </Form.Item>

        <Form.Item name="icon" label="图标" tooltip="支持 icones.js.org 和 Ant Design 图标">
          <IconPicker placeholder="点击选择图标" />
        </Form.Item>

        <Form.Item name="path" label="路由路径" tooltip="目录/菜单必填，按钮不需要">
          <Input placeholder="例如：/system/menu" />
        </Form.Item>

        <Form.Item name="component" label="组件路径" tooltip="菜单必填，目录和按钮不需要">
          <Input placeholder="例如：System/Menu" />
        </Form.Item>

        <Form.Item name="permission" label="权限标识" tooltip="用于权限控制，建议格式：resource:action">
          <Input placeholder="例如：menu:read" />
        </Form.Item>

        <Form.Item name="orderNum" label="排序" initialValue={0}>
          <InputNumber placeholder="数字越小越靠前" min={0} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item name="visible" label="是否可见" valuePropName="checked" initialValue={true}>
          <Switch checkedChildren="显示" unCheckedChildren="隐藏" />
        </Form.Item>

        <Form.Item name="status" label="状态" valuePropName="checked" initialValue={true}>
          <Switch checkedChildren="启用" unCheckedChildren="禁用" />
        </Form.Item>

        <Form.Item name="cache" label="是否缓存" valuePropName="checked" initialValue={false} tooltip="页面缓存，保留页面状态">
          <Switch checkedChildren="缓存" unCheckedChildren="不缓存" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default MenuFormModal;

